#!/Pub/Apps/bin/Rscript
pkgs <- c("pdftools", "stringr", "purrr", "argparse")
pkg_check <- \(pkgs) {
    pkg_v <- \(pkg_name) {
        packageVersion(pkg_name)
    }
    for (i in pkgs) {
        tryCatch(pkg_v(i), error = \(e) {
            message(paste0("Need pkg \033[4ma", i, "\033[24m, try to install it via utils::install.packages()\n"))
            utils::install.packages(i, repos = "https://mirrors.bfsu.edu.cn/CRAN/")
        })
    }
}
pkg_check(pkgs)
suppressPackageStartupMessages(library(purrr))
suppressPackageStartupMessages(library(argparse))

wrp <- "
    基于R语言R包pdftools，将PDF转化PNG。
  注：
    - 如果遇到转化失败的pdf会直接跳过，不影响其他pdf转化。
    - 如果文件夹里某些pdf是多页，则默认只转化第一页。
    - 如果pdf图形很复杂，则转化较慢。"

# create parser object-------
parser <- ArgumentParser(
    description = wrp,
    formatter_class = "argparse.RawDescriptionHelpFormatter",
    usage = "pdf2png -h; pdf2png ./example.pdf; pdf2png ./example_dir/"
)
parser$add_argument("path",
    action = "store",
    default = "NULL", nargs = 1,
    help = "必要参数。如果是路径，会在该路径下自动检索所有的pdf文件并转化；如果是单个pdf件路径，转化单个pdf"
)
parser$add_argument("-d", "--dpi",
    action = "store",
    default = 300, metavar = "",
    help = "分辨率，[default %(default)s]"
)
parser$add_argument("-pa", "--page",
    action = "store",
    default = "NULL", metavar = "",
    help = "转化pdf中的哪几页，只有path参数为单个文件时，该参数起效。"
)

# parser$print_help()
args <- parser$parse_args()


if(args$path == 'NULL'){
    parser$print_help()
    q(status = 1)
}

pdf2png_s <- function(pdf = NULL, dpi = 300, pages = NULL) {
    if (stringr::str_detect(pdf, "\\.pdf")) {
        filename <- stringr::str_replace_all(pdf, "pdf", "png")
    }

    if (stringr::str_detect(pdf, "\\.PDF")) {
        filename <- stringr::str_replace_all(pdf, "PDF", "png")
    }

    if (!is.null(pages)) {
        filename <- stringr::str_replace_all(filename, ".png", stringr::str_glue("_{pages}.png"))
    }

    if (is.null(pages)) {
        pages <- 1
    }

    if(!is.null(pages)){
        pages <- pages:pages
    }

    pdftools::pdf_convert(
        pdf = pdf, format = "png", pages = pages, filenames = filename,
        dpi = dpi, verbose = F
    )
}

pdf2png_q <- quietly(pdf2png_s)
pdf2png <- safely(pdf2png_q)

args$dpi <- as.integer(args$dpi)

jd <- file_test("-d", args$path)
jf <- file_test("-f", args$path)

if (isTRUE(jd)) {
    pdfs <- list.files(args$path, pattern = "\\.pdf", recursive = T, full.names = T)
    walk(pdfs, ~ pdf2png(.x, dpi = args$dpi), .progress = T)
}

if (isTRUE(jf)) {
    if(args$page == 'NULL'){
        args$page <- 1
    }

    pdf2png(pdf = args$path, dpi = args$dpi, pages = args$page) %>% invisible()
}

if (jd + jf == 0) {
    cli::cli_alert_danger("{.path {args$path}} 可能有问题，检查一下.")
    q(status = 1)
}


